﻿#if !LITE
using System;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class OfficeToPdfConverter : Actor<DestinationItem, OfficeToPdfOption>
    {
        private static Collection<OfficeConverter> converters = new Collection<OfficeConverter>();

        static OfficeToPdfConverter()
        {
            converters.Add(new DocConverter());
            converters.Add(new XlsConverter());
            converters.Add(new PptConverter());
        }

        protected override void Prepare()
        {
            if (!PdfCreator.Exists)
            {
                throw new PdfCreatorDoesntExist();
            }

            PdfCreatorOption.ChangeOptions();

            OfficeConverter.ConvertOption = pageOption;
        }

        protected virtual void ExtractHyperlinks()
        {
        }

        private OfficeConverter ChooseConverter()
        {
            foreach (OfficeConverter converter in converters)
            {
                if (converter.Format.IsOneOf(workItem.Source))
                {
                    return converter;
                }
            }

            return null;
        }

        protected override void Work()
        {
            base.Work();

            OfficeConverter.WorkItem = workItem;
            OfficeConverter converter = ChooseConverter();
            converter.Convert();
        }

        protected override void Finish()
        {
            try
            {
                //for some unknown reasons of Microsoft Office Applicatons, we need to stop for a while so
                //that the office can quit safely
                Helper.Sleep(Global.RestTime);
                PdfCreatorOption.ResetOptions();
                PdfCreator.Deactivate();

                foreach (OfficeConverter convert in converters)
                {
                    convert.CloseApplication();
                }
            }
            finally
            {
                base.Finish();
            }
        }
    }
}

#endif
